import 'dart:io';

import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqlite3_flutter_libs/sqlite3_flutter_libs.dart';
// ignore: depend_on_referenced_packages
import 'package:path/path.dart';

class SqilteEngine {
  // 消息数据库
  Future<Database> initMessageDatabase() async {
    if (Platform.isWindows || Platform.isLinux) {
      // Initialize FFI
      databaseFactoryOrNull = null;
      sqfliteFfiInit();
    }
    databaseFactoryOrNull = null;
    applyWorkaroundToOpenSqlite3OnOldAndroidVersions();
    databaseFactory = databaseFactoryFfi;
    final dir = await getApplicationDocumentsDirectory();
    if (!await dir.exists()) {
      await dir.create(recursive: true);
    }
    final database = openDatabase(
      join(dir.path, 'message.db'),
      version: 1,
      onCreate: (db, version) {
        return db.execute(
          '''CREATE TABLE message(id INTEGER PRIMARY KEY, 
          senderId INTEGER, 
          receptorId INTEGER,
          userName TEXT,
          userImg TEXT,
          context TEXT,
          create_time TEXT)''',
        );
      },
    );
    return database;
  }

  // 缓存数据库
  Future<Database> initCacheDatabase() async {
    if (Platform.isWindows || Platform.isLinux) {
      // Initialize FFI
      sqfliteFfiInit();
    }
    applyWorkaroundToOpenSqlite3OnOldAndroidVersions();
    databaseFactory = databaseFactoryFfi;
    final dir = await getApplicationDocumentsDirectory();
    if (!await dir.exists()) {
      await dir.create(recursive: true);
    }
    final database = openDatabase(
      join(dir.path, 'message.db'),
      version: 1,
      onCreate: (db, version) {
        return db.execute(
          'CREATE TABLE cache(id INTEGER PRIMARY KEY, key TEXT, value TEXT,create_time TEXT)',
        );
      },
    );
    return database;
  }
}
